<template>
  <div>
    <!-- 标题 -->
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <!-- error显示 -->
    <p v-if="error" style="color: red">
      {{ error }}
    </p>
  </div>
</template>

<script>
import Schema from "async-validator";
export default {
  inject: ["form"],
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: {
      type: String,
    },
  },
  data() {
    return {
      error: "",
    };
  },
  methods: {
    /**
     *  执行具体校验
     */
    validate() {
      //1、获取校验规则
      const rules = this.form.rules[this.prop];
      //2、获取数据模型
      const value = this.form.model[this.prop];
      //3、校验对象创建
      const descripe = { [this.prop]: rules };
      //4、创建校验器
      const shema = new Schema(descripe);
      //5、校验
      shema.validate({ [this.prop]: value }, (errors) => {
        if (errors) {
          this.error = errors[0].message;
        } else {
          this.error = "";
        }
      });
    },
  },
  mounted() {
    let that = this;
    //   监听校验事件
    this.$on("validate", () => {
      that.validate();
    });
  },
};
</script>